import type { Reducer, Effect } from 'umi';
import { history } from 'umi';

import { accountLogin } from '@/services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { message } from 'antd';
import { baseUrl } from '../../config/httpUrl';
import { AUTH_TOKEN } from '@/utils/request';

export interface StateType {
  status?: 'ok' | 'error';
  statusCode?: 200 | 500;
  statusMsg?: string;
  type?: string;
  currentAuthority?: 'user' | 'guest' | 'admin';
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'login',

  state: {
    status: undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // Login successfully
      if (response.code === 200) {
        // const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        const { redirect } = params as { redirect: string };
        localStorage.setItem('token', response.result.token)
        localStorage.setItem('userInfo', JSON.stringify(response.result.userInfo))
        localStorage.setItem('uid', response.result.userInfo.id)
        // window.location.href = '/admin';
        window.location.href = '/web/teacher-admin';
        // if (redirect) {
        //   const redirectUrlParams = new URL(redirect);
        //   console.log(redirectUrlParams)
        //   if (redirectUrlParams.origin === urlParams.origin) {
        //     redirect = redirect.substr(urlParams.origin.length);
        //     if (redirect.match(/^\/.*#/)) {
        //       redirect = redirect.substr(redirect.indexOf('#') + 1);
        //     }
        //   } else {
        //     window.location.href = '/';
        //     return;
        //   }
        // }
        // history.replace(redirect || '/admin');
        history.replace(redirect || '/web/teacher-admin');
      } else {
        message.error(response.message)
      }
    },

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      localStorage.removeItem(AUTH_TOKEN)
      localStorage.removeItem('username')
      if (!redirect) {
        window.location.href = baseUrl!.login;
      }
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      // setAuthority(payload.currentAuthority);
      setAuthority('admin');
      return {
        ...state,
        statusCode: payload.status,
        statusMsg: payload.msg,
        status: payload.status,
        type: payload.type,
        detail: payload
      };
    },
  },
};

export default Model;
